package cn.com.zetatech.maple.core.resource;

import cn.com.zetatech.maple.rule.RuleParser;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author cheng.cao@zetatech.com.cn
 */
@Slf4j
public class RuleLoader {

    /**
     * 加载所有规则文件
     */
    public static int load() {
        long start = System.currentTimeMillis();
        String ruleBasePath = System.getProperty("MAPLE_CONF_DIR") + "/rules";
        File[] ruleFiles = new File(ruleBasePath).listFiles(pathname -> pathname.getName().endsWith(".xml"));
        // 兼容处理，有限获取${MAPLE_CONF_DIR}/rules下的文件
        // 获取失败则尝试按照${MAPLE_HOME}/conf/rules下的文件
        if (ruleFiles == null || ruleFiles.length == 0) {
            ruleFiles = new File(System.getProperty("MAPLE_HOME") + "/conf/rules").listFiles(pathname -> pathname.getName().endsWith(".xml"));
        }
        log.info("加载规则文件开始");
        int successNum = 0;
        for (File ruleFile : ruleFiles) {
            boolean loadSuccess = load(ruleFile.getAbsolutePath());
            if (loadSuccess) {
                successNum++;
            }
        }
        long end = System.currentTimeMillis();
        long stopwatch = end - start;
        log.info("加载规则文件完成! 规则文件个数: {}, 成功加载个数: {}, 耗时: {} ms",
                ruleFiles.length,
                successNum,
                stopwatch);
        return successNum;
    }

    /**
     * 加载指定规则文件
     */
    public static boolean load(String file) {
        try {
            RuleParser.load(file);
            log.info("规则文件:{}", file);
            return true;
        } catch (Exception e) {
            log.info("加载规则文件异常:{}", file, e);
            return false;
        }
    }
}
